<?php
/**
 * Created by PhpStorm.
 * User: Marmot
 * Date: 2018/5/8
 * Time: 13:51
 */
namespace app\admin\controller;
use think\Controller;
use app\admin\model\Common;
//左导航
class Nav extends Base{
    //导航列表
    public function lst(){
        $nav = new Common();
        //导航排序
        if ($this->request->isPost()){
            $data = $this->request->param('data');
            $id = $this->request->param('id');
            $d['nav_sort'] = $data;
            $where['id'] = $id;
            $r = $nav->table('d_nav')->where($where)->update($d);
            if ($r){
                echo 111;
            }else{
                echo 222;
            }
        }else {
//            输出列表
            $res = $nav->get_nav();
            $this->assign('nav_arr', $res);
            return $this->fetch();
        }
    }

    //排序

    //添加导航
    public function add(){
        $nav = new Common();
        $res = $nav->table('d_nav')->field('nav_name,id')->where('nav_parent=0')->select();
        $this->assign('nav_parent',$res);
        if($this->request->isPost()){
            $data = $this->request->param();
            $validate = new \app\admin\validate\Nav;
            if(!$validate->check($data)){
                $this->error($validate->getError());
            }else{
                $r = $nav->table('d_nav')->insert($data);
                if ($r){
                    $this->success('添加成功','nav/lst');
                }
            }
        }
        return $this->fetch();
    }
    //编辑导航
    public function edit(){
        //收集表单
        $nav = new Common();
        $id = $this->request->param('id');
        if ($this->request->isPost()){
            $data = $this->request->param();
            $validate = new \app\admin\validate\Nav;
            if (!$validate->check($data)){
                $this->error($validate->getError());
            }else{
                $r = $nav->table('d_nav')->where('id='.$id)->update($data);
                if ($r){
                    $this->success('修改成功','nav/lst');
                }
            }
        }else{
            $res = $nav->table('d_nav')->where('id='.$id)->find();
            $this->assign('nav_arr',$res);
            //父级导航
            $res = $nav->table('d_nav')->field('nav_name,id')->where('nav_parent=0')->select();
            $this->assign('nav_parent',$res);
        }

        return $this->fetch();
    }
    //删除导航
    public function delete(){
        $id = $this->request->param('id');
        $nav = new Common();
        $res = $nav->table('d_nav')->where('nav_parent='.$id)->find();
        if($res){
            $this->error('删除失败，该导航下存在子导航');
        }else{
            $r = $nav->table('d_nav')->where('id='.$id)->delete();
            if ($r){
                $this->success('删除成功');
            }
        }
        return $this->fetch();
    }
}